<template>
  <div class="appointments-page">
    <van-nav-bar
      title="预约管理"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 状态切换 -->
    <van-tabs v-model:active="active" sticky>
      <van-tab title="全部" name="all" />
      <van-tab title="待就诊" name="0" />
      <van-tab title="已完成" name="1" />
      <van-tab title="已取消" name="2" />
    </van-tabs>

    <!-- 预约列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-for="item in appointmentList" :key="item.id" class="appointment-item">
          <van-cell-group inset>
            <van-cell center>
              <template #title>
                <div class="patient-info">
                  <span class="name">{{ item.patientName }}</span>
                  <van-tag :type="getStatusType(item.status)">
                    {{ getStatusText(item.status) }}
                  </van-tag>
                </div>
              </template>
              <template #label>
                <div class="appointment-time">
                  预约时间：{{ formatDateTime(item.appointmentTime) }}
                </div>
              </template>
            </van-cell>
            <van-cell title="就诊类型" :value="item.type" />
            <van-cell v-if="item.description" title="病情描述" :label="item.description" />
            <div class="cell-footer">
              <template v-if="item.status === 0">
                <van-button 
                  size="small" 
                  type="primary"
                  @click="handleStatusChange(item.id, 1)"
                >
                  完成就诊
                </van-button>
                <van-button 
                  size="small" 
                  type="danger" 
                  @click="handleStatusChange(item.id, 2)"
                >
                  取消预约
                </van-button>
              </template>
              <van-button 
                size="small" 
                type="info" 
                plain
                @click="showDetail(item)"
              >
                查看详情
              </van-button>
            </div>
          </van-cell-group>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 详情弹窗 -->
    <van-dialog
      v-model:show="showDetailDialog"
      title="预约详情"
      :show-confirm-button="false"
    >
      <template v-if="currentDetail">
        <van-cell-group>
          <van-cell title="患者姓名" :value="currentDetail.patientName" />
          <van-cell title="联系电话" :value="currentDetail.phone" />
          <van-cell title="预约时间" :value="formatDateTime(currentDetail.appointmentTime)" />
          <van-cell title="就诊类型" :value="currentDetail.type" />
          <van-cell title="病情描述" :label="currentDetail.description" />
          <van-cell title="创建时间" :value="formatDateTime(currentDetail.createTime)" />
          <van-cell v-if="currentDetail.status === 1" title="就诊记录" :label="currentDetail.medicalRecord" />
          <van-cell v-if="currentDetail.status === 2" title="取消原因" :label="currentDetail.cancelReason" />
        </van-cell-group>
      </template>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showConfirmDialog, showToast } from 'vant'
import { getAppointmentList, updateAppointmentStatus } from '@/api/doctor'
import { formatDateTime } from '@/utils/format'

const router = useRouter()

// 列表状态
const active = ref('all')
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const appointmentList = ref([])

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 10,
  status: ''
})

// 详情弹窗
const showDetailDialog = ref(false)
const currentDetail = ref(null)

// 获取预约列表
const getList = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      status: active.value === 'all' ? '' : active.value
    }
    const { data } = await getAppointmentList(params)
    
    if (refreshing.value) {
      appointmentList.value = []
      refreshing.value = false
    }
    
    appointmentList.value.push(...data.records)
    
    if (appointmentList.value.length >= data.total) {
      finished.value = true
    }
    queryParams.page++
  } catch (error) {
    console.error('获取预约列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 刷新列表
const onRefresh = () => {
  finished.value = false
  queryParams.page = 1
  getList()
}

// 加载更多
const onLoad = () => {
  getList()
}

// 处理预约
const handleStatusChange = async (id, status) => {
  const message = status === 1 ? '确认完成就诊？' : '确认取消预约？'
  showConfirmDialog({
    title: '提示',
    message,
  }).then(async () => {
    try {
      await updateAppointmentStatus(id, status)
      showToast('操作成功')
      onRefresh()
    } catch (error) {
      console.error('操作失败:', error)
      showToast('操作失败')
    }
  })
}

// 查看详情
const showDetail = (item) => {
  currentDetail.value = item
  showDetailDialog.value = true
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待就诊',
    1: '已完成',
    2: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'primary',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'default'
}

// 监听状态切换
watch(active, () => {
  queryParams.page = 1
  finished.value = false
  appointmentList.value = []
  getList()
})
</script>

<style lang="scss" scoped>
.appointments-page {
  min-height: 100vh;
  background-color: $background-color;
  
  .appointment-item {
    margin: 12px;
    
    .patient-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .name {
        font-size: 16px;
        font-weight: 500;
        color: $text-color;
      }
    }
    
    .appointment-time {
      color: $text-color-secondary;
      font-size: 14px;
      margin-top: 4px;
    }
    
    .cell-footer {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      padding: 8px 16px;
      border-top: 1px solid $border-color;
    }
  }
}
</style> 